﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Threading;
using System.IO;
using DomainInfoLib;



//1、域名check
//接口采用HTTP，POST，GET协议：
//调用URL：http://panda.www.net.cn/cgi-bin/check.cgi
//参数名称：area_domain 值为标准域名，例：hichina.com
//调用举例：http://panda.www.net.cn/cgi-bin/check.cgi?area_domain=hichina.com
//返回XML：
//<?xml version="1.0" encoding="gb2312"?>
//<property>
//<returncode>200</returncode>
//<key>2zher3r3r.com</key>
//<original>210 : Domain name is available</original>
//</property> 
//返回XML结果说明：
//returncode=200 表示接口返回成功
//key=***.com表示当前check的域名
//original=210 : Domain name is available     表示域名可以注册
//original=211 : Domain name is not available  表示域名已经注册
//original=212 : Domain name is invalid   表示域名参数传输错误
//2、域名info
//接口采用HTTP，POST，GET协议：
//调用URL：http://whois.hichina.com/cgi-bin/whois
//参数名称：domain  值为标准域名，例：hichina.com
//调用举例：http://whois.hichina.com/cgi-bin/whois?domain= hichina.com
//返回文本：其中在字符<pre>与字符</pre>之间即为域名信息内容。

namespace DomainInfoDigger
{
    public partial class FrmDig : Form
    {
        public FrmDig()
        {
            InitializeComponent();



        }

        private event EventHandler DigCompleted;


        Digger digger;


        private void Form1_Load(object sender, EventArgs e)
        {
            DigCompleted += new EventHandler(digger_DigCompleted); 
            
            digger = new Digger();

            digger.DoneOne += new GottenRegisteInfoHandle(digger_DoneOne);

            LoadParams();
        }

        private void LoadParams()
        {
            BaseInfo baseInfo=new BaseInfo();

            //AddToUI(textBox_Keywords, baseInfo.Keywords);
            
            //AddToUI(textBox_Keywords, baseInfo.SpellCodes);

            uC_ListBox_KeyWords.SetList(baseInfo.SpellCodes);

            AddToUI(textBox_PreFixes,baseInfo.PreFixes);

            AddToUI(textBox_SurFixes, baseInfo.SurFixes);
        }


        void digger_DoneOne(QueryItem item)
        {

            if (this.InvokeRequired)
            {
                GottenRegisteInfoHandle _myInvoke = new GottenRegisteInfoHandle(GetARegisterInfo);
                this.Invoke(_myInvoke, item);
            }
            else
            {
                GetARegisterInfo(item);
            }

           
        }

        void GetARegisterInfo(QueryItem item)
        {
            toolStripProgressBar1.Value++;

            toolStripStatusLabel2.Text = toolStripProgressBar1.Value.ToString() + "/" + toolStripProgressBar1.Maximum.ToString();

            if (toolStripProgressBar1.Value == toolStripProgressBar1.Maximum) digger_DigCompleted(null, null);

            if (IsJustAvaliable() && item.Avaliable() == false) return;

            ListViewItem viewItem = BuildListViewItem(item);

            listView_RegisteInfo.Items.Add(viewItem);
        }

        private ListViewItem BuildListViewItem(QueryItem item)
        {
            ListViewItem viewItem = new ListViewItem();

            ListViewGroup group = GetGroup(item.KeyWord);

            viewItem.Group = group;

            viewItem.Text = item.DomainFullName;

            viewItem.SubItems.Add(item.Domain); //+ "★☆"

            viewItem.SubItems.Add(item.DomainName);

            viewItem.SubItems.Add(item.Avaliable().ToString());

            viewItem.SubItems.Add(item.RegisteInfo.Response);

            viewItem.ImageKey = "Registed";

            if (item.Avaliable().HasValue)
            {
                viewItem.ImageKey = "UnRegisted";
            }
            return viewItem;
        }


        void digger_DigCompleted(object sender, EventArgs e)
        {
            MessageBox.Show("搜索完成");
        }


        private bool IsJustAvaliable()
        {
            return !checkBox_UnavaliableIsVisable.Checked;
        }






        private ListViewGroup GetGroup(string GroupName)
        {
            if (listView_RegisteInfo.Groups[GroupName] == null)
            {
                listView_RegisteInfo.Groups.Add(GroupName, GroupName);
            }

            return listView_RegisteInfo.Groups[GroupName];
        }

        private List<string> GetSurFixes()
        {
            List<string> keyWords = new List<string>();

            //keyWords.Add("");

            foreach (string line in textBox_SurFixes.Lines)
            {
                if (string.IsNullOrEmpty(line)) continue;

                keyWords.Add(line.Trim());
            }

            return keyWords;
        }

        //private List<string> GetKeyWords()
        //{
        //    List<string> keyWords = new List<string>();

        //    foreach (string line in textBox_Keywords.Lines)
        //    {
        //        if (string.IsNullOrEmpty(line)) continue;
        //        keyWords.Add(line.Trim());
        //    }

        //    return keyWords;
        //}

        private List<string> GetKeyWords()
        {
            List<string> keyWords = uC_ListBox_KeyWords.GetList() as List<string>;

            return keyWords;
        }

        private List<string> GetCheckedDomains()
        {
            List<string> domains = new List<string>();

            foreach (object item in checkedListBox_Domians.CheckedItems)
            {
                domains.Add(item.ToString());
            }
            return domains;
        }



        private void button_Cancel_Click(object sender, EventArgs e)
        {
            try
            {
                if (digger.Cancel())
                    MessageBox.Show("搜索已停止");
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
            
        }

        QueryGroup _QueryGroup = new QueryGroup();

        private void button_BuildQueryItems_Click(object sender, EventArgs e)
        {
            _QueryGroup = new QueryGroup();

            _QueryGroup.AddKeyWords(GetKeyWords());

            _QueryGroup.AddDomains(GetCheckedDomains());
            
            _QueryGroup.AddSurFixes(GetSurFixes());

            _QueryGroup.AddPreFixes(GetPreFixes());

            _QueryGroup.DoQueryKeyWord(GetIsQueryKeyWord());

            _QueryGroup.DoQueryPreFixesAndKeyWord(GetIsPreFixesAndKeyWord());

            _QueryGroup.DoQueryKeyWordsAndSurFixes(GetIsKeyWordsAndSurFixes());

            _QueryGroup.DoQueryPreFixesAndKeyWordsAndSurFixes(GetIsPreFixesAndKeyWordsAndSurFixes());

            _QueryGroup.BuildItems();


        }

        private bool GetIsPreFixesAndKeyWordsAndSurFixes()
        {
            return checkBox_PFixAndKeyAndSFix.Checked;
        }

        private bool GetIsKeyWordsAndSurFixes()
        {
            return checkBox_KeyWordAndSurFix.Checked;
        }

        private bool GetIsPreFixesAndKeyWord()
        {
            return checkBox_PreFixAndKeyWord.Checked;
        }

        private bool GetIsQueryKeyWord()
        {
            return checkBox_OnlyKeword.Checked;
        }

        private List<string> GetPreFixes()
        {
            List<string> preFixes = new List<string>();

            foreach (string line in textBox_PreFixes.Lines)
            {
                if (string.IsNullOrEmpty(line)) continue;

                preFixes.Add(line.Trim());
            }

            return preFixes;
        }

        private void button_Search_Click(object sender, EventArgs e)
        {

            PrepareSearch();

            //digger.dig(keyInfos);

            digger.SetThreadCount(GetThreadCount());

            digger.dig(_QueryGroup);


        }

        private int GetThreadCount()
        {
            return int.Parse(textBox_ThreadCount.Text.Trim());
        }

        private void PrepareSearch()
        {
            listView_RegisteInfo.Items.Clear();

            toolStripProgressBar1.Visible = true;
            
            toolStripProgressBar1.Value = 0;

            toolStripProgressBar1.Maximum = _QueryGroup.Count;

            toolStripStatusLabel1.Text = "开始搜索";

            toolStripStatusLabel2.Text = toolStripProgressBar1.Value.ToString() + "/" + toolStripProgressBar1.Maximum.ToString();
        }

        private void button_LoadPreFixes_Click(object sender, EventArgs e)
        {
            LoadFileParms(textBox_PreFixes);
        }

        private void LoadFileParms(TextBox textBox)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string[] pathes = openFileDialog1.FileNames;

                List<string> paramsList = GetParamsFromFiles(pathes);

                AddToUI(textBox,paramsList);
            }
        }

        private List<string> GetParamsFromFiles(string[] pathes)
        {
            List<string> Lines = new List<string>();
            
            foreach (string path in pathes)
            {
                Lines.AddRange(BaseInfo.GetParamsFromFile(path));
            }

            return Lines;
        }

        private void AddToUI(TextBox textBox, List<string> paramsList)
        {
            foreach (string paramName in paramsList)
            {
                if (!string.IsNullOrEmpty(paramName))
                {
                    textBox.Text +=  paramName+"\r\n";
                }
                
            }
        }


        private void button_LoadKeywords_Click(object sender, EventArgs e)
        {
            LoadFileParms(textBox_Keywords);


        }

        private void button_LoadSurFixes_Click(object sender, EventArgs e)
        {
            LoadFileParms(textBox_SurFixes);
        }

        private void button_SingleSearch_Click(object sender, EventArgs e)
        {
            string KeyWord = textBox_SingleKeyWord.Text.Trim();
            RegisterInfo res = DiggerServer.GetResponse(KeyWord);
            textBox_SingleResult.Text = res.Response + "\r\n" + res.Avaliable.Value.ToString();


        }




    }
}
